import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('../views/Home.vue')
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/frontend',
    name: 'Frontend',
    component: () => import('@/views/Frontend.vue')
  },
  {
    path: '/backend',
    name: 'Backend',
    component: () => import('../views/Backend.vue'),
    meta: { requiresAdmin: true },
    redirect: '/backend/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/dashboard/Dashboard.vue')
      },
      {
        path: 'user-list',
        name: 'UserList',
        component: () => import('../views/user/UserList.vue')
      },
      {
        path: 'user-role',
        name: 'RoleManagement',
        component: () => import('../views/role/RoleManagement.vue'),
        meta: {
          requiresAuth: true,
          title: '角色管理'
        }
      },
      {
        path: 'movie-list',
        name: 'MovieList',
        component: () => import('../views/movie/MovieList.vue'),
        meta: {
          requiresAuth: true,
          title: '电影列表'
        }
      },
      {
        path: 'movie-crawler',
        name: 'MovieCrawler',
        component: () => import('../views/movie/MovieCrawler.vue'),
        meta: {
          requiresAuth: true,
          title: '电影采集'
        }
      },
      {
        path: 'movie-clean',
        name: 'MovieClean',
        component: () => import('../views/movie/MovieClean.vue'),
        meta: {
          requiresAuth: true,
          title: '数据清洗'
        }
      },
      {
        path: 'analysis/box-office',
        name: 'BoxOfficeAnalysis',
        component: () => import('../views/analysis/BoxOfficeAnalysis.vue'),
        meta: {
          requiresAuth: true,
          title: '票房分析'
        }
      },
      {
        path: 'analysis/showing',
        name: 'ShowingAnalysis',
        component: () => import('../views/analysis/ShowingAnalysis.vue'),
        meta: {
          requiresAuth: true,
          title: '排片分析'
        }
      },
      {
        path: 'settings',
        name: 'SystemSettings',
        component: () => import('../views/settings/SystemSettings.vue'),
        meta: {
          requiresAuth: true,
          title: '系统设置'
        }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 检查登录状态
  const checkLoginStatus = () => {
    try {
      const tokenData = localStorage.getItem('token')
      const userData = localStorage.getItem('user')
      
      if (!tokenData || !userData) {
        return false
      }

      const token = JSON.parse(tokenData)
      const user = JSON.parse(userData)

      if (!token.access || !user.id) {
        return false
      }

      return { token, user }
    } catch (e) {
      console.error('登录状态检查错误:', e)
      return false
    }
  }

  // 不需要登录的路由
  const publicRoutes = ['/login', '/register']
  if (publicRoutes.includes(to.path)) {
    const loginStatus = checkLoginStatus()
    if (loginStatus) {
      // 如果已登录，重定向到首页
      next(loginStatus.user.is_admin ? '/backend/dashboard' : '/frontend')
    } else {
      next()
    }
    return
  }

  // 检查登录状态
  const loginStatus = checkLoginStatus()
  if (!loginStatus) {
    localStorage.clear()
    ElMessage.error('请先登录')
    next('/login')
    return
  }

  // 需要管理员权限的路由
  if (to.matched.some(record => record.meta.requiresAdmin)) {
    const { user } = loginStatus
    if (!(user.is_admin || user.is_superuser)) {
      ElMessage.error('您没有访问权限')
      next('/frontend')
      return
    }
  }

  next()
})

export default router 